import logging
import os

from . import settings

# 定义日志文件输出格式
formatter = logging.Formatter("%(asctime)s - %(filename)s line %(lineno)d - %(levelname)s: %(message)s")

def log_file(log_path=None):
    # 创建写入文件的handler
    config = settings.config
    if log_path is None:
        if 'log' in config and 'path' in config['log']:
            log_path = config['log']['path']
        elif 'base_dir' in config:
            log_path = os.path.join(config["base_dir"], 'logs')
        else:
            log_path = os.path.join(os.getcwd(), 'logs')
    os.makedirs(log_path, exist_ok=True)

    levels = {'debug': logging.DEBUG, 'info': logging.INFO, 'warn': logging.WARN, 'error': logging.ERROR}
    fhs = []
    for name, level in levels.items():
        fh = logging.FileHandler(os.path.join(log_path, f'{name}.log'))
        fh.setLevel(level)
        fh.setFormatter(formatter)
        fhs.append(fh)

    return fhs


def log_cmd():
    # 创建控制台handler
    ch = logging.StreamHandler()
    ch.setLevel(logging.INFO)
    ch.setFormatter(formatter)
    return ch


def set_logger(log_path=None):
    # 创建logger
    logger = logging.getLogger()
    logger.setLevel(logging.INFO)
    # 将logger添加到handler里面
    for fh in log_file(log_path):
        logger.addHandler(fh)
    logger.addHandler(log_cmd())
